﻿using Castle.DynamicProxy;
using CNKI.TPI.Web.Admin.IDAO;
using CNKI.TPI.Web.Admin.Model;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Report.IBLL;
using CNKI.TPI.Web.Report.IDAO;
using CNKI.TPI.Web.Search.IDAO;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace CNKI.TPI.Web.Report.BLL
{
    class DBStatisticsService : BaseService, IDBStatisticsService
    {
        IDBStatisticsDAO dBStatisticsDAO = null;
        ICategoryDAO categoryDAO = null;
        IUserDBDAO userDBDAO = null;
        public DBStatisticsService(IDBStatisticsDAO dBStatisticsDAO, ICategoryDAO categoryDAO, IUserDBDAO userDBDAO)
        {
            this.dBStatisticsDAO = this.generator.CreateInterfaceProxyWithTarget<IDBStatisticsDAO>(dBStatisticsDAO, new IInterceptor[] { new LogInterceptor() });
            this.categoryDAO = this.generator.CreateInterfaceProxyWithTarget<ICategoryDAO>(categoryDAO, new IInterceptor[] { new LogInterceptor() });
            this.userDBDAO = this.generator.CreateInterfaceProxyWithTarget<IUserDBDAO>(userDBDAO, new IInterceptor[] { new LogInterceptor() });
        }

        public DataTable GetDBStatisticsInfo(DateTime? startDate, DateTime? endDate, string clsCode, string dBName)
        {
            DataTable dt = InitDBStatisticsInfoTable();
            DataTable dBlist = GetDataBaseList();
            DataRow[] filteredDBList = null;
            if (string.IsNullOrEmpty(clsCode) && string.IsNullOrEmpty(dBName))
            {
                filteredDBList = dBlist.Select();
            }
            else if ((!string.IsNullOrEmpty(clsCode)) && string.IsNullOrEmpty(dBName))
            {
                filteredDBList = dBlist.Select("CLSCODE = '" + clsCode + "'");
            }
            else if (string.IsNullOrEmpty(clsCode) && (!string.IsNullOrEmpty(dBName)))
            {
                filteredDBList = dBlist.Select("DBNAME LIKE '%" + dBName + "%'");
            }
            else
            {
                filteredDBList = dBlist.Select("CLSCODE = '" + clsCode + "' and DBNAME LIKE '%" + dBName + "%'");
            }
            DataTable dbAccessInfo = dBStatisticsDAO.GetDBAccessInfo(filteredDBList.Select(c => c["DBCODE"].ToString()).ToList(), startDate, endDate);

            foreach (DataRow item in filteredDBList)
            {
                decimal download = 0;
                decimal view = 0;
                decimal searchcount = 0;
                if (dbAccessInfo != null && dbAccessInfo.Rows.Count > 0)
                {
                    DataRow[] drList = dbAccessInfo.Select("DbCode = '" + item["DBCode"] + "'");
                    if (drList != null && drList.Length > 0)
                    {
                        searchcount = (decimal)drList[0][1];
                        download = (decimal)drList[0][2];
                        view = (decimal)drList[0][3];
                    }
                }
                //根据数据库DBCODE 查找数据库总记录数

                DataRow dr = dt.NewRow();
                dr[0] = item["CLSNAME"];
                dr[1] = item["DBNAME"];
                dr[2] = GetDBFieldCount(item["DBCODE"].ToString());
                dr[3] = searchcount;
                dr[4] = download;
                dr[5] = view;
                dr[6] = (DateTime.Parse((string)item["CREATETIME"])).ToString("yyyy/MM/dd");
                dt.Rows.Add(dr);
            }
            return dt;
        }

        private DataTable GetDataBaseList()
        {
            DataTable result = InitDBTable();
            try
            {
                //或者所有发布数据库列表
                IList<SYS_CMS_DATABASE> dbList = userDBDAO.GetDatabaseList();
                //dbList = dbList.Where(c => (c.TemplateID != videoLibID && c.TemplateID != picLibID && c.TemplateID != audioLibID)).ToList();

                IList<SYS_CMS_DATABASE_CLS> databaseCLS = categoryDAO.GetDatabaseCLSType();
                if (databaseCLS != null && databaseCLS.Count > 0)
                {
                    IList<SYS_CMS_DATABASE_CLS_NODE> databaseCLSNode = categoryDAO.GetDatabaseCLSNodeType(databaseCLS[0].SysID);
                    if (databaseCLSNode == null || databaseCLSNode.Count == 0)
                    {
                        return null;
                    }

                    IList<SYS_CMS_DATABASE_CLS_DB> databaseCLSDb = categoryDAO.GetDatabaseCLSDBType(databaseCLS[0].SysID, databaseCLSNode.Select(p => p.Code));
                    if (databaseCLSDb == null || databaseCLSDb.Count == 0)
                    {
                        return null;
                    }

                    IList<SYS_CMS_DATABASE> database = categoryDAO.GetDatabaseByCode(databaseCLSDb.Select(p => p.DatabaseCode), flage:0);
                    if (database == null || database.Count == 0)
                    {
                        return null;
                    }

                    foreach (SYS_CMS_DATABASE item in database)
                    {
                        IEnumerable<SYS_CMS_DATABASE_CLS_DB> temp = databaseCLSDb.Where(p => p.DatabaseCode == item.DatabaseCode);
                        foreach (SYS_CMS_DATABASE_CLS_DB item1 in temp)
                        {
                            IEnumerable<SYS_CMS_DATABASE_CLS_NODE> item2 = databaseCLSNode.Where(p => p.Code == item1.ClsCode);
                            foreach (SYS_CMS_DATABASE_CLS_NODE item3 in item2)
                            {
                                if (!item3.DatabaseList.Contains(item))
                                {
                                    DataRow dr = result.NewRow();
                                    dr[0] = item3.Code;
                                    dr[1] = item3.Name;
                                    dr[2] = item.SysID;
                                    dr[3] = item.DatabaseCode;
                                    dr[4] = item.DatabaseName;
                                    dr[5] = item.CreateDate;
                                    result.Rows.Add(dr);
                                    RemoveDB(dbList, item.SysID);
                                }
                            }
                        }
                    }
                    if (dbList != null && dbList.Count > 0)
                    {
                        foreach (SYS_CMS_DATABASE item in dbList)
                        {
                            DataRow dr = result.NewRow();
                            dr[0] = "other";
                            dr[1] = "其他";
                            dr[2] = item.SysID;
                            dr[3] = item.DatabaseCode;
                            dr[4] = item.DatabaseName;
                            dr[5] = item.CreateDate;
                            result.Rows.Add(dr);
                        }
                    }
                }
                else
                {
                    if (dbList != null && dbList.Count > 0)
                    {
                        foreach (SYS_CMS_DATABASE item in dbList)
                        {
                            DataRow dr = result.NewRow();
                            dr[0] = "all";
                            dr[1] = "全部";
                            dr[2] = item.SysID;
                            dr[3] = item.DatabaseCode;
                            dr[4] = item.DatabaseName;
                            dr[5] = item.CreateDate;
                            result.Rows.Add(dr);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        private static DataTable InitDBTable()
        {
            DataTable result = new DataTable();
            result.Columns.Add("CLSCODE");
            result.Columns.Add("CLSNAME");
            result.Columns.Add("DBID");
            result.Columns.Add("DBCODE");
            result.Columns.Add("DBNAME");
            result.Columns.Add("CREATETIME");
            return result;
        }

        private void RemoveDB(IList<SYS_CMS_DATABASE> dbList, int dbid)
        {
            for (int i = 0; i < dbList.Count; i++)
            {
                if (dbList[i].SysID == dbid)
                {
                    dbList.RemoveAt(i);
                    break;
                }
            }
        }

        private static DataTable InitDBStatisticsInfoTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CategoryName");
            dt.Columns.Add("DBName");
            dt.Columns.Add("DataCount");
            dt.Columns.Add("SearchCount");
            dt.Columns.Add("DownloadCount");
            dt.Columns.Add("ViewCount");
            dt.Columns.Add("CreateTime");
            return dt;
        }

        /// <summary>
        /// 获取分类
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE_CLS_NODE> GetTemplateClS()
        {
            IList<SYS_CMS_DATABASE_CLS_NODE> result = null;
            try
            {
                IList<SYS_CMS_DATABASE_CLS> databaseCLS = categoryDAO.GetDatabaseCLSType();
                if (databaseCLS != null && databaseCLS.Count > 0)
                {
                    IList<SYS_CMS_DATABASE_CLS_NODE> databaseCLSNode = categoryDAO.GetDatabaseCLSNodeType(databaseCLS[0].SysID);
                    if (databaseCLSNode != null && databaseCLSNode.Count > 0)
                    {
                        result = databaseCLSNode;
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 根据数据库编码获取数据库中记录数
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        private int GetDBFieldCount(string dbcode)
        {
            //SELECT count(*) as sumfield FROM PERIODCJFD_METADATA
            return dBStatisticsDAO.GetDBFieldCount(dbcode);
        }
    }
}
